<template>
  <div  class="form-wrapper">
    <el-form ref="elForm" :model="formData" :rules="rules" label-position="top" class="form-container">
      <el-form-item label="评议监督员" >
        <el-input v-model="this.user.nickName" readonly></el-input>
      </el-form-item>
      <!-- 更新后的行政村下拉菜单 -->
      <el-form-item label="行政村" prop="village">
        <el-select v-model="formData.village" placeholder="请选择行政村" clearable @change="onVillageChange">
          <el-option
            v-for="item in villageList"
            :key="item.villageId"
            :label="item.villageName"
            :value="item.villageId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评议员" prop="senator">
        <el-select v-model="formData.senator" placeholder="请选择评议员" clearable >
          <el-option
            v-for="item in senatorList"
            :key="item.reviewerId"
            :label="item.reviewerName"
            :value="item.reviewerId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评议类型" prop="review_type">
        <el-select v-model="formData.review_type" placeholder="请选择评议类型" clearable>
          <el-option v-for="(item, index) in review_typeOptions" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评议时间" prop="time">
        <el-date-picker v-model="formData.time" type="date" placeholder="请选择评议时间" clearable></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 弹窗组件 -->
    <el-dialog  :visible.sync="dialogVisible" :title="villageTitle" fullscreen center class="form-wrapper" :before-close="beforeDialogClose">
      <div class="dialog-info" >
        <span><strong>评议监督员：</strong>{{ user.nickName }}</span>
        <span><strong>评议员：</strong>{{ getSenatorName(formData.senator) }}</span>
        <span><strong>评议类型：</strong>{{ getReviewTypeName(formData.review_type) }}</span>
        <span><strong>评议时间：</strong>{{ formData.time ? formData.time.toLocaleDateString() : '' }}</span>
      </div>
      <!-- 村民信息表格 -->
      <el-table :data="households[householdIndex] || []">
        <el-table-column label="村民编号" align="center" prop="villagerId" />
        <el-table-column label="户籍号" align="center" prop="villagerDomicileNumber" />
        <el-table-column label="姓名" align="center" prop="villagerName" />
        <el-table-column label="性别" align="center" prop="villagerSex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.villagerSex"/>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="villagerAge" />
        <el-table-column label="与户主关系" align="center" prop="relationship" />
        <el-table-column label="主信贷人标志" align="center" prop="villagerMainMark">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.villagerMainMark"/>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center">
          <template slot-scope="scope">
            {{ scope.row.villagerNumber.substring(0, 6) + '********' + scope.row.villagerNumber.substring(14) }}
          </template>
        </el-table-column>
        <el-table-column label="居住地址" align="center" prop="villagerAddress" />
        <el-table-column label="信息备注" align="center" prop="villagerNotes" />
      </el-table>

      <!--评议情况表单-->
      <el-form ref="form" :model="form" :rules="ruless" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="村名字" prop="reviewVillageName">
              <el-input v-model="form.reviewVillageName" placeholder="请输入村名字" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评议户籍号" prop="reviewDomicileNumber">
              <el-input v-model="form.reviewDomicileNumber" placeholder="请输入评议户籍号" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="主信贷人姓名" prop="reviewName">
          <template v-if="form.mainCreditPersonSelected">
            <el-input v-model="form.reviewName" readonly></el-input>
          </template>
          <template v-else>
            <el-select v-model="form.selectedMainCreditPerson" placeholder="请选择主信贷人" @change="onMainCreditPersonChange">
              <el-option v-for="villager in currentHouseholdVillagers" :key="villager.value" :label="villager.label" :value="villager.value"></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="身份证号" prop="reviewNumber">
          <el-input v-model="form.reviewNumber" readonly></el-input>
        </el-form-item>
        <el-row>
          <el-form-item label="是否了解信贷人情况" prop="reviewKnow1">
            <el-select v-model="form.reviewKnow1" placeholder="请选择是否了解信贷人情况">
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="是否存在以下情况" prop="reviewKnow2" v-if="reviewUnderstand === 'Y'">
          <el-select v-model="form.reviewKnow2" placeholder="请选择是否存在以下情况">
            <el-option
              v-for="dict in dict.type.bank_know2"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <template v-if="!disableFurtherQuestions">
          <el-form-item label="农村房产情况" prop="reviewKnow3" v-if="formData.review_type !== 2">
            <el-select v-model="form.reviewKnow3" placeholder="请选择农村房产情况">
              <el-option
                v-for="dict in dict.type.bank_know3"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城区有无房产" prop="reviewKnow4" v-if="formData.review_type !== 2">
            <el-select v-model="form.reviewKnow4" placeholder="请选择城区有无房产">
              <el-option
                v-for="dict in dict.type.bank_know4"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="有无车辆" prop="reviewKnow5" v-if="formData.review_type !== 2">
            <el-select v-model="form.reviewKnow5" placeholder="请选择有无车辆">
              <el-option
                v-for="dict in dict.type.bank_know5"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年收入" prop="reviewKnow6" v-if="formData.review_type !== 2">
            <el-select v-model="form.reviewKnow6" placeholder="请选择年收入">
              <el-option
                v-for="dict in dict.type.bank_know6"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工作类型" prop="reviewKnow7" v-if="formData.review_type !== 2">
            <el-select v-model="form.reviewKnow7" placeholder="请选择工作类型">
              <el-option
                v-for="dict in dict.type.bank_know7"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="主营项目" prop="reviewKnow8" v-if="formData.review_type !== 2">
            <el-input v-model="form.reviewKnow8" placeholder="请输入主营项目" />
          </el-form-item>
        </template>
        <el-form-item label="备注" prop="reviewNotes" >
          <el-input v-model="form.reviewNotes" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <!-- 分页按钮 -->
      <div class="dialog-footer">
        <el-button @click="showPreviousHousehold" :disabled="householdIndex <= 0">上一户</el-button>
        <el-button @click="showNextHousehold" :disabled="householdIndex >= households.length - 1">下一户</el-button>
        <el-button type="primary" @click="submitReviewForm" :disabled="householdIndex < households.length - 1">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {listVillage,getVillage} from "@/api/bank/village";
import {listSenator} from "@/api/bank/senator";
import { getUserProfile } from "@/api/system/user";
import {listVillagers,updateVillagers} from "@/api/bank/villagers";
import {addReview} from "@/api/bank/review";
import {getDomicileByNumber,updateDomicile,listDomicile} from "@/api/bank/domicile";

export default {
  dicts: ['sys_user_sex','sys_yes_no','bank_know2', 'bank_know4', 'bank_know3', 'bank_know6', 'bank_know5', 'sys_yes_no', 'bank_know7'],
  data() {
    return {
      reviewForms: [],
      form: this.initEmptyForm(),
      householdIndex: 0, // 当前显示的户籍的索引
      households: [], // 按户籍号分组的村民信息
      dialogVisible: false, // 控制弹窗显示的变量
      formData: {
        village: '',
        review_type: '',
        senator: '',
        time: ''
      },
      domicileInfo:{},
      user: {}, // 当前用户
      villageList: [], // 原始行政村列表数据
      filteredVillageList: [], // 过滤后的行政村列表
      senatorList: [], // 评议员列表
      villagersList: [], // 用于在弹窗中显示的村民列表
      currentHouseholdVillagers: [], // 当前户的所有村民列表
      reviewUnderstand: 'Y', // 用于存储“是否了解信贷人情况”的选择
      // 增加一个属性来控制“是否存在以下情况”的可选性和必填性
      reviewCondition: '', // 用于存储“是否存在以下情况”的选择
      rules: {
        village: [{ required: true, message: '请选择行政村', trigger: 'change' }],
        review_type: [{ required: true, message: '请选择评议类型', trigger: 'change' }],
        senator: [{ required: true, message: '请选择评议员', trigger: 'change' }],
        time: [{ required: true, message: '请选择评议时间', trigger: 'change' }]
      },
      review_typeOptions: [],
      // 表单校验
      ruless: {
        reviewName: [
          { required: true, message: "主信贷人姓名不能为空", trigger: "blur" }
        ],
        reviewNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
        reviewType: [
          { required: true, message: "评议类型不能为空", trigger: "blur" }
        ],
        reviewerId: [
          { required: true, message: "评议员不能为空", trigger: "blur" }
        ],
        reviewSupervisor: [
          { required: true, message: "评议监督员不能为空", trigger: "blur" }
        ],
        reviewTime: [
          { required: true, message: "评议时间不能为空", trigger: "blur" }
        ],
        reviewKnow1: [
          { required: true, message: "是否了解信贷人情况不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getCurrentUser();
  },
  computed: {
    // 动态生成弹窗标题
    villageTitle() {
      const village = this.villageList.find(item => item.villageId === this.formData.village);
      return village ? `${village.villageName}评议表` : '评议表';
    },
    // 根据选择动态显示提示或者使字段不可编辑
    disableFurtherQuestions() {
      return this.reviewUnderstand === 'N' || (this.reviewCondition !== '' && this.reviewCondition !== '14');
    },
    requireFurtherQuestions() {
      return this.reviewUnderstand === 'Y' && this.reviewCondition === '14';
    },
  },
  // 使用 watch 来确保表单数据与当前显示的户同步
  watch: {
    householdIndex(newIndex, oldIndex) {
      this.loadFormForCurrentHousehold();
    },
    // 监视选择的变化来动态更新表单验证规则
    'form.reviewKnow1': function(newVal) {
      this.reviewUnderstand = newVal;
      this.updateFormRules();
    },
    'form.reviewKnow2': function(newVal) {
      this.reviewCondition = newVal;
      this.updateFormRules();
    }
  },
  methods: {
    initEmptyForm() {
      return {
        reviewVillageName: '',
        reviewDomicileNumber: '',
        reviewName: '',
        reviewNumber: '',
        reviewType: '',
        reviewerId: '',
        reviewSupervisor: '',
        reviewTime: '',
        reviewKnow1: '',
        reviewKnow2: '',
        reviewKnow3: '',
        reviewKnow4: '',
        reviewKnow5: '',
        reviewKnow6: '',
        reviewKnow7: '',
        reviewKnow8: '',
        reviewNotes: '',
        selectedMainCreditPerson: null, // 选中的主信贷人ID
        mainCreditPersonSelected: false, // 是否已选择主信贷人
        // ... 其他需要的字段
      };
    },
    // 获取当前用户信息
    getCurrentUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.getVillageList();
      });
    },
    // 获取行政村列表
    getVillageList() {
      listVillage({pageSize:1000000}).then(response => {
        // 确认response.rows是一个数组且不为空
        if (Array.isArray(response.rows) && response.rows.length) {
          // 过滤出当前用户管理的行政村
          if (this.user.userId != 17 && this.user.userId != 1) {
            this.villageList = response.rows.filter(village => village.superVisorId == this.user.userId);
          } else {
            // 如果是特定ID，则不进行过滤，直接使用全部行政村数据
            this.villageList = response.rows;

          }
        } else {
          // 如果response.rows不是数组或者为空，可以在这里处理
          console.log("No village data received or not in expected format:", response.rows);
        }
        // 根据过滤后的行政村ID获取评议员信息
        this.getSenatorList();
      });
    },
    // 获取评议员列表
    getSenatorList(villageId) {
      listSenator({pageSize:10000000}).then(response => {
        this.senatorList = response.rows.filter(senator =>
          senator.villageId === villageId
        );
      });
    },

    // 获得评议类型列表
    getReviewtypeList(villageId) {
      // 先清空现有的评议类型选项
      this.review_typeOptions = [];
      listDomicile({pageSize:100000000}).then(response => {
        const domiciles = response.rows.filter(d => d.villageId === villageId && d.domicileLabel !== "2");
        let canRegularReview = false;
        let canQualityReview = false;
        let canWhiteReview = false;
        // 根据villageId获取行政村的roundNumber属性
        getVillage(villageId).then(villageResponse => {
          const roundNumber = villageResponse.data.roundNumber;

          switch (roundNumber) {
            case "0":
              // 检查是否存在至少一条户籍信息的twoSenatorId为空
              canRegularReview = domiciles.some(d => !d.twoSenatorId||d.twoSenatorId=='0');
              // 检查是否存在至少一条户籍信息的domicileQualitySenatorId为空
              canQualityReview = domiciles.some(d => !d.domicileQualitySenatorId||d.domicileQualitySenatorId=='0');
              break;
            case "1":
              // 检查是否存在至少一条户籍信息的oneSenatorId为空
              canRegularReview = domiciles.some(d => !d.oneSenatorId||d.oneSenatorId=='0');
              // 检查是否存在至少一条户籍信息的domicileQualitySenatorId为空
              canQualityReview = domiciles.some(d => !d.domicileQualitySenatorId||d.domicileQualitySenatorId=='0');
              break;
            case "2":
              // 检查是否存在至少一条户籍信息的oneSenatorId为空
              canRegularReview = domiciles.some(d => !d.oneSenatorId||d.oneSenatorId=='0');
              break;
            default:
              console.log("Unexpected roundNumber value:", roundNumber);
          }
          canWhiteReview = domiciles.some(d => d.whiteSenatorId=='0');
          console.log("fuyi", canWhiteReview);
          // 根据判断结果更新评议类型选项
          if (canRegularReview) {
            this.review_typeOptions.push({ label: "普通评议", value: 1 });
          }
          if (canQualityReview) {
            this.review_typeOptions.push({ label: "品质评议", value: 2 });
          }
          if(!canRegularReview && !canQualityReview && canWhiteReview)
          {
            this.review_typeOptions.push({ label: "白名单复议", value: 3 });
          }
        }).catch(error => {
          console.error("Error fetching village data:", error);
        });
      }).catch(error => {
        console.error("Error fetching domicile data:", error);
      });
    },

    // 当行政村选项改变时触发
    onVillageChange(newVillageId) {
      this.formData.senator = ''; // 清除已选择的评议员
      this.formData.review_type = '';//清除已选择的评议类型
      if (newVillageId) {
        // 如果选择了行政村，获取该村的评议员列表
        this.getSenatorList(newVillageId);
        // 如果选择了行政村，获取该村的评议类型列表
        this.getReviewtypeList(newVillageId);
      } else {
        // 如果没有选择行政村，清空评议员列表
        this.senatorList = [];
        this.review_typeOptions = [];
      }
    },

    // 提交表单并显示弹窗
    submitForm() {
      this.$refs.elForm.validate(valid => {
        if (valid) {
          this.fetchVillagersForVillage(this.formData.village);
          this.dialogVisible = true; // 验证通过后显示弹窗
        }
      });
    },
    //提交弹窗中的表单
    // 根据选定的行政村获取村民信息，并按户籍号分组，然后过滤
    fetchVillagersForVillage(villageId) {
      if (villageId) {
        listVillagers({ 'bankVillage.villageId': villageId,pageSize:100000000}).then(response => {
          this.villagersList = response.rows.filter(villager => villager.villageId == villageId);
          this.groupVillagersByHousehold(this.villagersList);
          // 调用新方法来过滤户籍
          this.filterHouseholdsByDomicileTag(villageId);
        }).catch(error => {
          console.error('Error fetching villagers:', error);
          this.$message.error('无法获取村民信息');
        });
      } else {
        this.villagersList = [];
        this.households = [];
      }
    },
    filterHouseholdsByDomicileTag(villageId) {


      getVillage(villageId).then(villageResponse => {
        const roundNumber = villageResponse.data.roundNumber;

        const promises = this.households.map(household => {
          const domicileNumber = household.length > 0 ? household[0].villagerDomicileNumber : null;
          if (domicileNumber) {
            return getDomicileByNumber(domicileNumber)
              .then(response => {
                // 根据roundNumber判断评议类型
                if (this.formData.review_type == '1') {
                  if ((roundNumber === "0" && (response.data.twoSenatorId == null || response.data.twoSenatorId=='0') &&response.data.domicileLabel == "0") ||
                    ((roundNumber === "1" || roundNumber === "2") && (response.data.oneSenatorId == null || response.data.oneSenatorId=='0') &&response.data.domicileLabel == "0")
                    ) {
                    return household;
                  }
                }
                // 检查是否为品质评议
                else if (this.formData.review_type == '2' && (response.data.domicileQualitySenatorId == null || response.data.domicileQualitySenatorId=='0') && response.data.domicileLabel == "0") {
                  return household;
                }
                // 检查是否为白名单评议
                else if (this.formData.review_type == '3' && response.data.whiteSenatorId == '0' && response.data.domicileLabel == '1') {
                  return household;
                }
                return null;
              })
              .catch(error => {
                console.error('Error fetching domicile info:', error);
                return null;
              });
          } else {
            return Promise.resolve(null);
          }
        });

        Promise.all(promises).then(filteredResults => {
          this.households = filteredResults.filter(result => result !== null);
          this.householdIndex = 0; // 重置为第一个符合条件的户籍
          if (this.households.length > 0) {
            this.loadFormForCurrentHousehold(); // 加载第一户的数据
          }
        });

      }).catch(error => {
        console.error('Error fetching village info:', error);
      });
    },

    // 将村民按户籍号分组
    groupVillagersByHousehold(villagersList) {
      const householdsMap = new Map();
      villagersList.forEach(villager => {
        if (!householdsMap.has(villager.villagerDomicileNumber)) {
          householdsMap.set(villager.villagerDomicileNumber, []);
        }
        householdsMap.get(villager.villagerDomicileNumber).push(villager);
      });
      this.households = Array.from(householdsMap.values());
      this.householdIndex = 0; // 重置为第一个户籍
    },

    // 保存当前户的表单数据
    saveCurrentForm() {
      this.reviewForms[this.householdIndex] = { ...this.form };
    },

    loadFormForCurrentHousehold() {
      if (this.reviewForms[this.householdIndex]) {
        this.form = { ...this.reviewForms[this.householdIndex] };
      } else {
        this.form = this.initEmptyForm();
        this.form.reviewVillageName = this.getVillageName(this.formData.village);
        this.form.reviewerId = this.formData.senator;
        this.form.reviewType = this.getReviewTypeName(this.formData.review_type);
        this.form.reviewSupervisor = this.user.nickName;
        this.form.reviewTime = this.formData.time ? this.formData.time.toLocaleDateString() : '';
      }

      const currentHousehold = this.households[this.householdIndex];
      if (currentHousehold && currentHousehold.length > 0) {
        this.currentHouseholdVillagers = currentHousehold
          .filter(villager => villager.villagerAge >= 22 && villager.villagerAge <= 59)
          .map(villager => ({
            label: villager.villagerName,
            value: villager.villagerId,
            villagerNumber: villager.villagerNumber,
          }));
        if (this.formData.time) {
          const date = new Date(this.formData.time); // 确保是一个Date对象
          this.form.reviewTime = date.toISOString().split('T')[0]; // 转换为YYYY-MM-DD格式
        } else {
          this.form.reviewTime = '';
        }
        // 检测当前户是否有已经标记为主信贷人的村民
        const mainCreditPerson = currentHousehold.find(villager => villager.villagerMainMark === "Y");
        if (mainCreditPerson) {
          // 如果有，则自动填充主信贷人信息
          this.form.reviewName = mainCreditPerson.villagerName;
          this.form.reviewNumber = mainCreditPerson.villagerNumber;
          this.form.selectedMainCreditPerson = mainCreditPerson.villagerId;
          this.form.mainCreditPersonSelected = true;
        } else {
          // 如果没有，则允许用户选择主信贷人
          this.form.mainCreditPersonSelected = false;
        }

        this.form.reviewDomicileNumber = currentHousehold[0].villagerDomicileNumber;
      } else {
        this.currentHouseholdVillagers = [];
        this.form.selectedMainCreditPerson = null;
        this.form.mainCreditPersonSelected = false;
      }
    },


    onMainCreditPersonChange(value) {
      // 通过value找到当前选中的村民信息
      const selectedVillager = this.currentHouseholdVillagers.find(villager => villager.value === value);
      if (selectedVillager) {
        // 更新表单中的主信贷人姓名
        this.form.reviewName = selectedVillager.label;
        // 更新表单中的主信贷人身份证号
        this.form.reviewNumber = selectedVillager.villagerNumber;

        //更新选中的主信贷人ID
        this.form.selectedMainCreditPerson = selectedVillager.value;
        // 标记已选择主信贷人
        this.form.mainCreditPersonSelected = true;
      } else {
        // 如果没有找到选中的村民，可以清除主信贷人信息或做其他处理
        console.error("Selected main credit person not found");
        this.form.reviewName = '';
        this.form.reviewNumber = '';
        this.form.selectedMainCreditPerson = null;
        this.form.mainCreditPersonSelected = false;
      }
    },
    updateFormRules() {
      if (this.disableFurtherQuestions) {
        // 清除后续所有选项的验证规则
        this.ruless.reviewKnow3 = [];
        this.ruless.reviewKnow4 = [];
        this.ruless.reviewKnow5 = [];
        this.ruless.reviewKnow6 = [];
        this.ruless.reviewKnow7 = [];
        this.ruless.reviewKnow8 = [];
        // 更多字段的规则清除...
      } else if (this.requireFurtherQuestions) {
        // 设置后续所有选项为必填，除了备注
        this.ruless.reviewKnow3 = [{ required: true, message: "该项为必填", trigger: "change" }];
        this.ruless.reviewKnow4 = [{ required: true, message: "该项为必填", trigger: "change" }];
        this.ruless.reviewKnow5 = [{ required: true, message: "该项为必填", trigger: "change" }];
        this.ruless.reviewKnow6 = [{ required: true, message: "该项为必填", trigger: "change" }];
        this.ruless.reviewKnow7 = [{ required: true, message: "该项为必填", trigger: "change" }];
        this.ruless.reviewKnow8 = [{ required: true, message: "该项为必填", trigger: "change" }];

        // 更多字段设置为必填...
      }

    },
    beforeDialogClose(done) {
      this.resetDialogForm();
      done(); // 关闭弹窗
    },
    resetDialogForm() {
      this.$refs.form.resetFields(); // 假设你的评议情况表单的 ref="form"
      this.reviewForms = []; // 重置评议表单数据
      this.dialogVisible = false; // 关闭弹窗
    },
    submitReviewForm() {
      this.saveCurrentForm();

      if (!this.isFormComplete(this.form)) {
        this.$message({
          message: '当前户籍评议表未填写完整，请继续填写',
          type: 'warning'
        });
        return; // 如果当前户的表单不完整，停止进一步操作
      }


      const updatePromises = this.reviewForms.map(form => {
        // 检查form.reviewKnow1是否为'Y'，且selectedMainCreditPerson是否被选中
        if (form.reviewKnow1 === 'Y' && form.selectedMainCreditPerson) {
          return updateVillagers({ villagerId: form.selectedMainCreditPerson, villagerMainMark: "Y" });
        }
        return Promise.resolve();
      });

      Promise.all(updatePromises).then(() => {
        const submitPromises = this.reviewForms.map(form => {
          let domicileUpdatePromise;

          if (form.reviewKnow1 === 'Y') {

            domicileUpdatePromise = getDomicileByNumber(form.reviewDomicileNumber).then(domicileInfo => {
              const creditAmount = this.calculateCreditAmount(form);

              if (form.reviewKnow2 !== '14') {
                // 'Y' and not '14'
                return updateDomicile({
                  domicileId: domicileInfo.data.domicileId,
                  domicileVillagerId: form.selectedMainCreditPerson,
                  domicileLabel: '2',
                });
              } else {
                // 'Y' and '14'
                if (form.reviewType === '品质评议') {
                  return updateDomicile({
                    domicileId: domicileInfo.data.domicileId,
                    domicileQuality: 'Y',
                    domicileQualitySenatorId: this.formData.senator,
                    domicileVillagerId: form.selectedMainCreditPerson,
                  });
                } else if(form.reviewType === '普通评议'){
                  // '普通评议'
                  if (!domicileInfo.data.oneSenatorId) {
                    return updateDomicile({
                      domicileId: domicileInfo.data.domicileId,
                      domicileVillagerId: form.selectedMainCreditPerson,
                      oneMoney: creditAmount,
                      oneSenatorId: this.formData.senator
                    });
                  } else {
                    return updateDomicile({
                      domicileId: domicileInfo.data.domicileId,
                      domicileVillagerId: form.selectedMainCreditPerson,
                      twoMoney: creditAmount,
                      twoSenatorId: this.formData.senator
                    });
                  }
                }
                else if(form.reviewType === '白名单复议'){
                  return updateDomicile({
                    domicileId: domicileInfo.data.domicileId,
                    whiteSenatorId: this.formData.senator,
                    whiteMoney: creditAmount,
                    domicileVillagerId: form.selectedMainCreditPerson,
                  });
                }
              }
            });
          } else {
            domicileUpdatePromise = Promise.resolve();
          }

          return domicileUpdatePromise.then(() => addReview({
            ...form,
            // Make sure to exclude keys that shouldn't be sent to the addReview API call
            selectedMainCreditPerson: undefined,
            mainCreditPersonSelected: undefined,
          }));
        });

        return Promise.all(submitPromises);
      }).then(() => {
        this.$message.success('所有评议记录添加成功');
        this.resetForm();
        this.resetDialogForm();
      }).catch(error => {
        console.error(error);
        this.$message.error('评议记录添加失败');
      });

    },
    calculateCreditAmount(form) {
      let creditAmount = 0;

      // 农村房产情况
      const ruralPropertyValues = { '0': 50000, '1': 30000, '2': 10000, '3': 0 };
      creditAmount += ruralPropertyValues[form.reviewKnow3] || 0;

      // 城区有无房产
      const urbanPropertyValues = { '0': 50000, '1': 0 };
      creditAmount += urbanPropertyValues[form.reviewKnow4] || 0;

      // 有无车辆
      const vehicleValues = { '0': 30000, '1': 0 };
      creditAmount += vehicleValues[form.reviewKnow5] || 0;

      // 年收入
      const incomeValues = { '0': 50000, '1': 40000, '2': 30000, '3': 10000 };
      creditAmount += incomeValues[form.reviewKnow6] || 0;

      // 工作类型
      const jobTypeValues = { '0': 20000, '1': 0 };
      creditAmount += jobTypeValues[form.reviewKnow7] || 0;

      // 最终模型测算额度
      return creditAmount;
    },


    // 检查表单是否完整
    isFormComplete(form) {
      // 基础必填项
      let requiredFields = ['reviewVillageName', 'reviewDomicileNumber', 'reviewName', 'reviewNumber', 'reviewType', 'reviewerId', 'reviewSupervisor', 'reviewTime', 'reviewKnow1'];
      // 如果了解信贷人情况，'reviewKnow2'也成为必填项
      if (form.reviewKnow1 === 'Y') {
        requiredFields.push('reviewKnow2');
        // 如果存在以下情况选择了'无'且为普通评议，那么除备注外其他都要填写
        if (form.reviewKnow2 === '14' && this.formData.review_type == 1) { // 假设'14'代表选项'无'
          requiredFields = requiredFields.concat(['reviewKnow3', 'reviewKnow4', 'reviewKnow5', 'reviewKnow6', 'reviewKnow7', 'reviewKnow8']);
        }
      }
      // 遍历requiredFields数组，确保每个必填字段都已被填写
      return requiredFields.every(field => form[field] !== null && form[field] !== '');
    },

    // 显示上一户的信息
    showPreviousHousehold() {
      this.saveCurrentForm(); // 保存当前户的表单
      if (this.householdIndex > 0) {
        this.householdIndex--;
        this.loadFormForCurrentHousehold();
      }
    },
    // 显示下一户的信息,// 当户切换时，保存当前表单并加载新的户的表单数据
    showNextHousehold() {
      if (!this.isFormComplete(this.form)) {
        this.$message({
          message: '当前户籍评议表未填写完整，请继续填写',
          type: 'warning'
        });
        return; // 如果当前户的表单不完整，停止进一步操作
      }

      if (this.householdIndex < this.households.length - 1) {
        this.saveCurrentForm(); // 保存当前户的表单
        this.householdIndex++;
        this.loadFormForCurrentHousehold();

      }
    },
    // 获取行政村名称
    getVillageName(villageId) {
      const village = this.villageList.find(item => item.villageId === villageId);
      return village ? village.villageName : '';

    },
    // 获取评议员名称
    getSenatorName(senatorId) {
      const senator = this.senatorList.find(item => item.reviewerId === senatorId);
      return senator ? senator.reviewerName : '';
    },
    // 获取评议类型名称
    getReviewTypeName(reviewTypeId) {
      const reviewType = this.review_typeOptions.find(item => item.value === reviewTypeId);
      return reviewType ? reviewType.label : '';
    },
    resetForm() {
      this.$refs.elForm.resetFields();
      this.dialogVisible = false; // 重置时关闭弹窗
    },
  }
};
</script>

<style scoped>
.form-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 20vh;
  background-color: #f5f5f5; /* 界面背景色 */
  padding: 20px;

}

.form-container {
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  background: white;
  width: 100%;
  max-width: 600px;
}

/* 确保输入框，下拉框和日期选择器填满它们的容器 */
.el-input,
.el-select .el-input .el-input__inner,
.el-date-picker .el-input__inner {
  border-radius: 5px;
  width: 40%;
}


.dialog-info {
  display: inline-flex;
  justify-content: space-between;
  width: 100%;
  max-width: 1400px; /* Adjust to suit your design */
  font-size: 20px; /* 示例字体大小，根据需要调整 */
}


</style>
